package com.zxy.ziems.server.collection.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxy.ziems.common.pojo.MeasureDataBean;
import com.zxy.ziems.common.pojo.MeasureDataDayBean;
import com.zxy.ziems.server.collection.mapper.*;
import com.zxy.ziems.server.collection.pojo.entity.CollectionDevicePropertyEntity;
import com.zxy.ziems.server.collection.pojo.entity.CollectionDevicePropertyParam;
import com.zxy.ziems.server.device.pojo.entity.DeviceEntity;
import com.zxy.ziems.server.device.pojo.vo.DataTypeVO;
import com.zxy.ziems.server.device.service.DataTypeService;
import com.zxy.ziems.server.device.service.DeviceService;
import com.zxy.ziems.server.domain.cim.EmsCimDayData;
import com.zxy.ziems.server.energy.mapper.DeviceMeasureDataDayMapper;
import com.zxy.ziems.server.energy.pojo.entity.DeviceMeasureDataDayEntity;
import com.zxy.ziems.server.mapper.EmsCimDayDataMapper;
import com.zxy.ziems.server.storage.service.MeasureDataDayStorageService;
import com.zxy.ziems.server.storage.service.MeasureDataStorageService;
import com.zxy.ziems.server.sync.enums.SyncEmsCimDayDataTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CollectionServiceImpl implements CollectionService {

    @Autowired
    private CollectionMapper collectionMapper;
    @Autowired
    private MeasureDataStorageService measureDataStorageService;
    @Autowired
    private MeasureDataDayStorageService measureDataDayStorageService;
    @Autowired
    private DLMapper dlMapper;
    @Autowired
    private WaterMapper waterMapper;
    @Autowired
    private CIMMapper cimMapper;
    @Autowired
    private ManualInputMapper manualInputMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private EmsCimDayDataMapper emsCimDayDataMapper;
    @Autowired
    private DeviceMeasureDataDayMapper deviceMeasureDataDayMapper;
    @Autowired
    private DataTypeService dataTypeService;
    @Autowired
    private WaterLiveMapper waterLiveMapper;

    @Override
    public void syncDevicePropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取FMCS对应设备数据【syncDevicePropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(CollectionDevicePropertyParam::getTag, v -> v));
        log.info("开始获取对应设备数据tagMap " + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 100;
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("tagMap size={}, val={}", tagMap.size(), JSONObject.toJSONString(tagMap));
        log.info("开始查询数据syncDevicePropertyValue collectionMapper.getByTags");
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            List<CollectionDevicePropertyEntity> partialData = collectionMapper.getByTags(splitMap.keySet());
            // 获取设备数据
            List<MeasureDataBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                String tag = d.getTag();
                String[] split = tag.split("\\.");
                tag = split[0] + "." + split[1].toUpperCase();
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(tag);
                if (!StringUtils.isEmpty(d.getValue()) && collectionDevicePropertyParam != null) {
                    data.add(collectionDeviceProperty2MeasureData(d, collectionDevicePropertyParam));
                }
            });

            measureDataStorageService.storageMeasureDataList(data);
        }


    }

    @Override
    public void syncWaterTotalDevicePropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取水科Total对应设备数据【syncDevicePropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(CollectionDevicePropertyParam::getTag, v -> v));
        log.info("开始获取对应设备数据tagMap " + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 100;
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("tagMap size={}, val={}", tagMap.size(), JSONObject.toJSONString(tagMap));
        log.info("开始查询数据syncDevicePropertyValue collectionMapper.getByTags");
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            List<CollectionDevicePropertyEntity> partialData = waterLiveMapper.getByTotalTags(splitMap.keySet());
            // 获取设备数据
            List<MeasureDataBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                String tag = d.getTag();
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(tag);
                if (!StringUtils.isEmpty(d.getValue()) && collectionDevicePropertyParam != null) {
                    data.add(collectionDeviceProperty2MeasureData(d, collectionDevicePropertyParam));
                }
            });

            measureDataStorageService.storageMeasureDataList(data);
        }


    }


    @Override
    public void syncDlDevicePropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取电力监控对应设备数据【syncDlDevicePropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(k -> k.getTag().trim(), v -> v));
        log.info("开始获取对应设备数据tagMap" + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 100;
//        List<CollectionDevicePropertyEntity> collectionData = new ArrayList<>();
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("Map切分为" + splitMaps.size() + "组");
        log.info("开始查询数据syncDlDevicePropertyValue dlMapper.getByTags");
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            List<CollectionDevicePropertyEntity> partialData = dlMapper.getByTags(splitMap.keySet());
            // 获取设备数据
            List<MeasureDataBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(d.getTag().replace("\\u0000", "").trim());
                if (!StringUtils.isEmpty(d.getValue())) {
                    data.add(collectionDeviceProperty2MeasureData(d, collectionDevicePropertyParam));
                }
            });

            measureDataStorageService.storageMeasureDataList(data);
        }
    }


    @Override
    public void syncWaterDlDevicePropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取水科纯废水对应设备数据【syncWaterDlDevicePropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(CollectionDevicePropertyParam::getTag, v -> v));
        log.info("开始获取对应设备数据tagMap " + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 100;
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("开始查询数据 syncWaterDevicePropertyValue waterMapper.getByTags");
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            List<CollectionDevicePropertyEntity> partialData = waterMapper.getByDlTags(splitMap.keySet());
            // 获取设备数据
            List<MeasureDataBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                String tag = d.getTag();
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(tag);
                if (!StringUtils.isEmpty(d.getValue()) && collectionDevicePropertyParam != null) {
                    data.add(collectionDeviceProperty2MeasureData(d, collectionDevicePropertyParam));
                }
            });

            measureDataStorageService.storageMeasureDataList(data);
        }
    }

    @Override
    public void syncWaterDevicePropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取水科(自来水,CDA,N2,H2)对应设备数据【syncWaterDevicePropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(CollectionDevicePropertyParam::getTag, v -> v));
        log.info("开始获取对应设备数据tagMap " + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 100;
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("开始查询数据 syncWaterDevicePropertyValue waterMapper.getByTags");
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            List<CollectionDevicePropertyEntity> partialData = waterMapper.getByTags(tagMap.keySet());
            // 获取设备数据
            List<MeasureDataDayBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                String tag = d.getTag();
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(tag);
                if (!StringUtils.isEmpty(d.getValue()) && collectionDevicePropertyParam != null) {
                    data.add(switchMeasureDataFormat(d, collectionDevicePropertyParam));
                }
            });
            measureDataDayStorageService.storageMeasureDataDayList(data);
        }
    }

    @Override
    public void syncWaterChemicalDevicePropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取水科纯废水化学品用量对应设备数据【syncWaterChemicalDevicePropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(CollectionDevicePropertyParam::getTag, v -> v));
        log.info("开始获取对应设备数据tagMap " + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 100;
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("开始查询数据 syncWaterChemicalDevicePropertyValue waterMapper.getByTags");
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            List<CollectionDevicePropertyEntity> partialData = waterMapper.getByChemicalTags(splitMap.keySet());
            // 获取设备数据
            List<MeasureDataBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                String tag = d.getTag();
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(tag);
                if (!StringUtils.isEmpty(d.getValue()) && collectionDevicePropertyParam != null) {
                    data.add(collectionDeviceProperty2MeasureData(d, collectionDevicePropertyParam));
                }
            });

            measureDataStorageService.storageMeasureDataList(data);
        }
    }

    @Override
    public void syncCIMDlDevicePropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取CIM对应设备电力数据【syncCIMDevicePropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(CollectionDevicePropertyParam::getTag, v -> v));
        log.info("开始获取对应设备数据tagMap " + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 1000;
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("开始查询数据syncCIMDevicePropertyValue cimMapper.getByDlTags");
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            List<CollectionDevicePropertyEntity> partialData = cimMapper.getByDlTags(splitMap.keySet());
            // 获取设备数据
            List<MeasureDataBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                String tag = d.getTag();
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(tag);
                if (!StringUtils.isEmpty(d.getValue()) && collectionDevicePropertyParam != null) {
                    data.add(collectionDeviceProperty2MeasureData(d, collectionDevicePropertyParam));
                }
            });

            measureDataStorageService.storageMeasureDataList(data);
        }

    }

    @Override
    public void syncCIMWaterDevicePropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取CIM对应设备水数据【syncCIMWaterDevicePropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(CollectionDevicePropertyParam::getTag, v -> v));
        log.info("开始获取对应设备数据tagMap " + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 1000;
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("开始查询数据syncCIMWaterDevicePropertyValue cimMapper.getByWaterTags");
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            List<CollectionDevicePropertyEntity> partialData = cimMapper.getByWaterTags(splitMap.keySet());
            // 获取设备数据
            List<MeasureDataBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                String tag = d.getTag();
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(tag);
                if (!StringUtils.isEmpty(d.getValue()) && collectionDevicePropertyParam != null) {
                    data.add(collectionDeviceProperty2MeasureData(d, collectionDevicePropertyParam));
                }
            });

            measureDataStorageService.storageMeasureDataList(data);
        }

    }

    @Override
    public void syncCIMGasDevicePropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取CIM对应设备气数据【syncCIMGasDevicePropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(CollectionDevicePropertyParam::getTag, v -> v));
        log.info("开始获取对应设备数据tagMap " + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 1000;
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("开始查询数据syncCIMGasDevicePropertyValue cimMapper.getByGasTags");
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            List<CollectionDevicePropertyEntity> partialData = cimMapper.getByGasTags(splitMap.keySet());
            // 获取设备数据
            List<MeasureDataBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                String tag = d.getTag();
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(tag);
                if (!StringUtils.isEmpty(d.getValue()) && collectionDevicePropertyParam != null) {
                    data.add(collectionDeviceProperty2MeasureData(d, collectionDevicePropertyParam));
                }
            });

            measureDataStorageService.storageMeasureDataList(data);
        }

    }

    @Override
    public void syncManualInputNaturalGasPropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取手工录入的天然气数据【syncManualInputNaturalGasPropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(CollectionDevicePropertyParam::getTag, v -> v));
        log.info("开始获取对应设备数据tagMap " + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 1000;
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("syncManualInputNaturalGasPropertyValue manualInputMapper.getByNaturalGasTags");
        // 只同步近n天内的数据
        String startTime = getLastNDayDate(7);
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            // 获取设备数据
            List<CollectionDevicePropertyEntity> partialData = manualInputMapper.getByNaturalGasTags(splitMap.keySet(), startTime);
            List<MeasureDataDayBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                String tag = d.getTag();
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(tag);
                if (!StringUtils.isEmpty(d.getValue()) && !StringUtils.isEmpty(d.getIncrementValue()) && collectionDevicePropertyParam != null) {
                    // 天然气存储的增量是每日消耗量
                    // 天然气的测量值是消耗总量
                    d.setIncrementValue(d.getIncrementValue());
                    data.add(switchMeasureDataFormat(d, collectionDevicePropertyParam));
                }
            });
            for (MeasureDataDayBean datum : data) {
                System.out.println(datum.getDeviceId() + "设备数据" + datum.getMeasureValue());
            }

            measureDataDayStorageService.storageMeasureDataDayList(data);
        }

    }

    @Override
    public void selectManualInputChemicalsPropertyValue(List<CollectionDevicePropertyParam> list) {
        log.info("开始获取手工录入的天然气数据【selectManualInputChemicalsPropertyValue】");
        if (CollectionUtils.isEmpty(list)) return;

        Map<String, CollectionDevicePropertyParam> tagMap = list.stream().collect(Collectors.toMap(CollectionDevicePropertyParam::getTag, v -> v));
        log.info("开始获取对应设备数据tagMap " + "tagMapSize:" + tagMap.size());
        // 设备数据量大，导致传入SqlServer的查询参数太多，无法完成查询，将数据分段查询并拼接
        int splitSize = 1000;
        List<Map<String, CollectionDevicePropertyParam>> splitMaps = splitMap(tagMap, splitSize);
        log.info("selectManualInputChemicalsPropertyValue manualInputMapper.getByChemicalsTags");
        // 只同步近n天内的数据
        String startTime = getLastNDayDate(7);
        for (Map<String, CollectionDevicePropertyParam> splitMap : splitMaps) {
            // 获取设备数据
            List<CollectionDevicePropertyEntity> partialData = manualInputMapper.getByChemicalsTags(splitMap.keySet(), startTime);
            List<MeasureDataDayBean> data = new ArrayList<>();
            if (CollectionUtils.isEmpty(partialData)) {
                return;
            }

            partialData.forEach(d -> {
                String tag = d.getTag();
                CollectionDevicePropertyParam collectionDevicePropertyParam = tagMap.get(tag);
                if (!StringUtils.isEmpty(d.getValue()) && !StringUtils.isEmpty(d.getIncrementValue()) && collectionDevicePropertyParam != null) {
                    // 天然气存储的增量是每日消耗量
                    // 天然气的测量值是消耗总量
                    d.setIncrementValue(d.getIncrementValue());
                    data.add(switchMeasureDataFormat(d, collectionDevicePropertyParam));
                }
            });
            for (MeasureDataDayBean datum : data) {
                System.out.println(datum.getDeviceId() + "设备数据" + datum.getMeasureValue());
            }

            measureDataDayStorageService.storageMeasureDataDayList(data);
        }
    }


    private MeasureDataBean collectionDeviceProperty2MeasureData(CollectionDevicePropertyEntity d, CollectionDevicePropertyParam p) {
        MeasureDataBean res = new MeasureDataBean();
        res.setDeviceId(p.getDeviceId());
        res.setDataTypeId(p.getDataTypeId());
        res.setUnitId(p.getUnitId());
        res.setMeasureTime(d.getMeasureTime());
        res.setMeasureValue(d.getValue());
        return res;
    }

    // 转换为
    private MeasureDataDayBean switchMeasureDataFormat(CollectionDevicePropertyEntity d, CollectionDevicePropertyParam p) {
        MeasureDataDayBean res = new MeasureDataDayBean();
        res.setDeviceId(p.getDeviceId());
        res.setDataTypeId(p.getDataTypeId());
        res.setUnitId(p.getUnitId());
        res.setMeasureTime(d.getMeasureTime());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = d.getMeasureTime().format(formatter);
        res.setMeasureDate(LocalDate.parse(format));
        res.setIncrementValue(d.getIncrementValue());
        res.setMeasureValue(d.getValue());
        return res;
    }

    /***
     * 切分map方法，与SqlServer连接，传入参数较多导致查询慢
     * @param originalMap
     * @param chunkSize
     * @return
     */
    public static List<Map<String, CollectionDevicePropertyParam>> splitMap(Map<String, CollectionDevicePropertyParam> originalMap, int chunkSize) {
        log.info("开始切分Map,Map大小为：" + originalMap.size() + "切分大小为：" + chunkSize);
        List<Map<String, CollectionDevicePropertyParam>> result = new ArrayList<>();
        Map<String, CollectionDevicePropertyParam> currentChunk = new HashMap<>();
        int count = 0;

        for (Map.Entry<String, CollectionDevicePropertyParam> entry : originalMap.entrySet()) {
            currentChunk.put(entry.getKey(), entry.getValue());
            count++;
            if (count == chunkSize) {
                result.add(currentChunk);
                currentChunk = new HashMap<>();
                count = 0;
            }
        }

        // 如果最后还有剩余的元素，也添加到结果中
        if (!currentChunk.isEmpty()) {
            log.info("切分完有剩余元素");
            result.add(currentChunk);
        }
        log.info("Map切分完成,份数为" + result.size());
        return result;
    }

    /**
     * 获取当前日期制定前n天的日期
     * 日期格式：2025-02-18
     */
    private static String getLastNDayDate(int days) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate lastDate = LocalDate.now().minusDays(days);
        return lastDate.format(formatter);
    }


    /**
     * 同步天数据去cim
     *
     * @param date
     */
    @Override
    public LocalDate syncDayDataToCim(LocalDate date) {

        log.info("开始同步天数据去cim");
        for (SyncEmsCimDayDataTypeEnum sysSyncEmsCimDayDataTypeEnum : SyncEmsCimDayDataTypeEnum.values()) {
            List<DeviceEntity> deviceEntityList = deviceService.listByTypeCode(sysSyncEmsCimDayDataTypeEnum.getCode());
            if (deviceEntityList.isEmpty()) {
                continue;
            }
            List<String> deviceIds = deviceEntityList.stream().map(m -> m.getId()).collect(Collectors.toList());

            List<DataTypeVO> dataTypeVOS = dataTypeService.listAll();


            // 通过设备id查询数据
            QueryWrapper<DeviceMeasureDataDayEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(DeviceMeasureDataDayEntity::getMeasureTime, date)
                    .in(DeviceMeasureDataDayEntity::getDeviceId, deviceIds);
            List<DeviceMeasureDataDayEntity> deviceMeasureDataDayEntities = deviceMeasureDataDayMapper.selectList(queryWrapper);

            // 处理存储cim表
            Map<String, DeviceEntity> deviceMap = deviceEntityList.stream().collect(Collectors.toMap(m -> m.getId(), m -> m));
            Map<String, DataTypeVO> dataTypeMap = dataTypeVOS.stream().collect(Collectors.toMap(m -> m.getId(), m -> m));
            List<EmsCimDayData> emsCimDayDataList = deviceMeasureDataDayEntities.stream().map(m ->
                    collectionDeviceProperty2CimData(m, sysSyncEmsCimDayDataTypeEnum.getCode(), deviceMap.get(m.getDeviceId()), dataTypeMap.get(m.getDataTypeId()))
            ).collect(Collectors.toList());

            if (emsCimDayDataList.size() > 0) {
                // 保存
                emsCimDayDataMapper.batchInsert(emsCimDayDataList);
            }

        }
        log.info("根据类型查询需要同步的数据结束");


        return date;
    }


    private EmsCimDayData collectionDeviceProperty2CimData(DeviceMeasureDataDayEntity deviceMeasureDataDayEntity, String classify, DeviceEntity device, DataTypeVO dataTypeVO) {
        device = device == null ? new DeviceEntity() : device;

        dataTypeVO = dataTypeVO == null ? new DataTypeVO() : dataTypeVO;

        EmsCimDayData res = new EmsCimDayData();
        res.setTagName(device.getCode());
        res.setTagClassify(classify);
        res.setDataType(dataTypeVO.getName());
        res.setDataValue(deviceMeasureDataDayEntity.getIncrementValue());
        res.setDataTime(deviceMeasureDataDayEntity.getMeasureTime());
        return res;
    }


}
